#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Time       :   14:04
# Author     : Y4
# Site       : 
# File       : backend_user_view.py
import uuid

from flask import Blueprint, request

from App.common.backend.get_admin_user import get_admin_user
from App.common.utils.constant import ADMINS
from App.common.utils.util import rerep, single_dict
from App.models.backend import AdminUser

from App.plugins import cache

adminUser = Blueprint('adminUser', __name__, url_prefix='/admin/user')

@adminUser.route('/login', methods=['POST'])
def login():
    username = request.form.get('username')
    password = request.form.get('password')

    user = get_admin_user(username)
    if not user:
        return rerep(msg='用户不存在', status=400)
    if not user.check_password(password):
        return rerep(msg='密码错误', status=400)
    token = uuid.uuid4().hex
    cache.set(token, user.uuid, timeout=60 * 60 * 24 * 7)
    return rerep(msg="登录成功", data=token)


@adminUser.route('/register', methods=['POST'])
def register():
    username = request.form.get('username')
    password = request.form.get('password')

    user = AdminUser()
    user.username = username
    user.password = password

    if username in ADMINS:
        user.is_super = True

    if not user.save():
        return rerep(msg="用户创建失败", status=400)

    # 不写或者写"all",返回全部..其余写的都是需要返回的字段
    return rerep(data=single_dict(user, "all"))
